package com.snail.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.snail.model.pojo.cart.BizRefundRequest;
import com.snail.result.PageResult;
import com.snail.result.Result;
import com.snail.service.MerchantRefundOrderService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/merchantRefunds")
public class MerchantRefundOrderController {

    @Autowired
    private MerchantRefundOrderService merchantRefundOrderService;

    /**
     * 分页查询商家端退款申请列表
     */
    @GetMapping("/list")
    public Result<PageResult<BizRefundRequest>> selectMerchantRefunds(
            @RequestBody BizRefundRequest refundRequest,
            Integer pageNum,
            Integer pageSize) {

        // 处理默认分页参数
        if (pageNum == null || pageNum <= 0) {
            pageNum = 1;
        }
        if (pageSize == null || pageSize <= 0) {
            pageSize = 10;
        }

        // 创建分页对象
        Page<BizRefundRequest> page = new Page<>(pageNum, pageSize);

        // 调用服务层方法查询
        var resultPage = merchantRefundOrderService.selectMerchantRefunds(page, refundRequest);

        // 构建分页结果并返回
        PageResult<BizRefundRequest> pageResult = PageResult.success(resultPage);
        return Result.success(pageResult);
    }

    /**
     * 查询单个退款申请详情
     */
    @GetMapping("/{refundId}")
    public Result<BizRefundRequest> getRefundDetail(@PathVariable Long refundId) {
        BizRefundRequest refund = merchantRefundOrderService.getRefundById(refundId);
        return refund != null ? Result.success(refund) : Result.failed("退款申请不存在");
    }

    /**
     * 商家处理退款申请
     */
    @PostMapping("/process")
    public Result<?> processRefund(@Valid @RequestBody BizRefundRequest refundRequest) {
        merchantRefundOrderService.handleRefund(refundRequest);
        return Result.success();
    }
    /**
     * 新增退款单在商家端
     */
    @PostMapping("/insertRefund")
    public void insertRefund(BizRefundRequest refundRequest) {
        merchantRefundOrderService.insertRefund(refundRequest);

    }
    //处理用户的退款申请
    @PutMapping("/updateRefund")
    public void updateRefund(BizRefundRequest refundRequest) {
        merchantRefundOrderService.updateRefund(refundRequest);
    }
}